package com.nl.controller.web.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.redis.RedisCluster;
import com.nl.controller.web.bean.ChangeData;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.mapper.SmsAreaMapper;
import com.nl.controller.xuyi.bean.XuYiCheckInfoBo;
import com.nl.controller.xuyi.mapper.XuYiCheckMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.bean.SmsMgrTemplateInfo;
import com.nl.controller.web.mapper.SmsMgrTemplateInfoMapper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SmsMgrTemplateInfoService {
	@Autowired
	private SmsMgrTemplateInfoMapper smsMgrTemplateInfoMapper;
	@Autowired
	private CommonService commonService;

	@Autowired
	private SmsAreaMapper smsAreaMapper;

	@Autowired
	private XuYiCheckMapper xuYiCheckMapper;

	@Autowired
	private ChangeSynchronizationInterfaceService changeSynchronizationInterfaceService;


	private String getStreamSeq() {
		String streamSeq = changeSynchronizationInterfaceService.getStreamSeq();
		log.debug("获取流水序列号：{}", streamSeq);
		return streamSeq;
	}

	@SystemServiceLog(description = "查询项目模板信息表", value = false)
	public PageInfo<SmsMgrTemplateInfo> find(int page, int limit, String cityId, String countyId, String mgrId,String mgrName,String mgrState,String templateState, String flag,String duty,String msisdn) {
		Map<String, Object> map = new HashMap<>();
		map.put("cityId", cityId);
		map.put("countyId", countyId);
		map.put("mgrId", mgrId);
		map.put("mgrName", mgrName);
		map.put("mgrState", mgrState);
		map.put("templateState", templateState);
		map.put("duty", duty);
		map.put("msisdn", msisdn);
		List<SmsMgrTemplateInfo> list;
		String cityExtId = "";// 扩展码
		String cityid= "";
		if (flag == null) {
			try {
				PageHelper.startPage(page, limit);
				list = smsMgrTemplateInfoMapper.find(map);
				for (SmsMgrTemplateInfo smsMgrTemplateInfo : list) {
					cityExtId = smsMgrTemplateInfo.getCityExtId();
					cityid = smsMgrTemplateInfo.getCityId();
					if("11".equals(cityid)){
						smsMgrTemplateInfo.setCityExtId("1065716061103"+cityExtId);
					}else{
						smsMgrTemplateInfo.setCityExtId("1065716061102"+cityExtId);
					}
					smsMgrTemplateInfo.setProvince("江苏");
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new SmsException("查询项目模板信息表出现异常");
			}
		} else {
			map.put("flag", 1);
			try {
				list = smsMgrTemplateInfoMapper.find(map);
				for (SmsMgrTemplateInfo smsMgrTemplateInfo : list) {
					smsMgrTemplateInfo.setProvince("江苏");
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("查询模板信息表");
				throw new SmsException("查询模板审核信息表");
			}
		}
		PageInfo<SmsMgrTemplateInfo> pageInfo = new PageInfo<SmsMgrTemplateInfo>(list);
		return pageInfo;
	}

	@SystemServiceLog(description = "获取项目id", value = false)
	public String getMgrId() {
		String mgrId;
		try {
			mgrId = smsMgrTemplateInfoMapper.getMgrId();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取项目id");
			throw new SmsException("获取项目id");
		}
		return mgrId;
	}
	@SystemServiceLog(description = "添加项目模板信息表", value = false)
	public int configureMgrTemplate(String cityId,String countyId,String name,String extId,String startTime,String endTime
			,String isLocal,int threshold,String isThreshold,String content,String tabIndex,String mgrId,String regionId,String regionType
			,String regionTypeValue,String mgrState,String templateState,String flag
			,String msisdn,String cycle,String cycleThreshold,String localDate,int checkNum,String mgrFlag){
		int result = 0;

		RedisCluster redisCluster=null;
		SmsMgrTemplateInfo smsMgrTemplateInfo = new SmsMgrTemplateInfo();
		smsMgrTemplateInfo.setCityId(cityId);
		smsMgrTemplateInfo.setCountyId(countyId);
		smsMgrTemplateInfo.setName(name);
		smsMgrTemplateInfo.setCityExtId(cityId+extId);
		smsMgrTemplateInfo.setStartDate(startTime);
		smsMgrTemplateInfo.setEndDate(endTime);
		smsMgrTemplateInfo.setIsLocal(isLocal);
		smsMgrTemplateInfo.setThreshold(threshold);
		smsMgrTemplateInfo.setIsThreshold(isThreshold);
		smsMgrTemplateInfo.setContent(content);
		smsMgrTemplateInfo.setContentType(tabIndex);
		smsMgrTemplateInfo.setId(mgrId);
		smsMgrTemplateInfo.setRegionId(regionId);
		smsMgrTemplateInfo.setRegionType(regionType);
		smsMgrTemplateInfo.setRegionTypeValue(regionTypeValue);
		smsMgrTemplateInfo.setMgrState(mgrState);
		smsMgrTemplateInfo.setTemplateState(templateState);
		smsMgrTemplateInfo.setMsisdn(msisdn);
		smsMgrTemplateInfo.setCycle(cycle);
		smsMgrTemplateInfo.setCycleThreshold(cycleThreshold);
		smsMgrTemplateInfo.setLocalDate(localDate);
		smsMgrTemplateInfo.setCheckNum(checkNum+"");
		smsMgrTemplateInfo.setTaskId("");
		smsMgrTemplateInfo.setMgrFlag(mgrFlag);
		//盱眙项目默认设置为已开户
		if("2".equals(mgrFlag)){
			smsMgrTemplateInfo.setOpenAccount("1");
		}else{
			//其他应急项目设置为开户
			smsMgrTemplateInfo.setOpenAccount("1");
		}

		if (("insert".equals(flag))||("xuYiInsert".equals(flag))) {
			try {
				redisCluster=new RedisCluster(GlobalConst.REDIS_CONFIG);
				//String keyName=mgrId+"hy";
				redisCluster.set(mgrId+"timeCount","0");
				redisCluster.set(mgrId+"dayCount","0");
				redisCluster.set(mgrId+"weekCount","0");
				redisCluster.set(mgrId+"monthCount","0");
				redisCluster.set(mgrId+"quarterCount","0");
				redisCluster.set(mgrId+"yearCount","0");
				redisCluster.set(mgrId+"totalCount","0");


				if("xuYiInsert".equals(flag)){
					if("0".equals(tabIndex)){
						//自定义短信内容需入项目短信内容审核表
						XuYiCheckInfoBo xuYiCheckInfoBo = new XuYiCheckInfoBo();
						xuYiCheckInfoBo.setType("4");
						xuYiCheckInfoBo.setMgrId(mgrId);
						xuYiCheckInfoBo.setMgrContent(content);
						xuYiCheckInfoBo.setCheckState("0");
						xuYiCheckInfoBo.setCheckNumber("0");
						xuYiCheckInfoBo.setOperator(msisdn);
						xuYiCheckMapper.addConTempCheckInfo(xuYiCheckInfoBo);
					}else{
						//使用短信模板不需要审核，将状态改为已审核
						smsMgrTemplateInfo.setTemplateState("2");
						//直接开启状态
						smsMgrTemplateInfo.setMgrState("0");


					}
					//基站临时表中数据插入基站正式表
					int insertResult = smsAreaMapper.addStation(mgrId);
					//上步操作成功，将临时表中的数据删除
					if(insertResult > 0){
						smsAreaMapper.delStationTemp(mgrId);
					}
				}

				result = smsMgrTemplateInfoMapper.insertMgrTemplate(smsMgrTemplateInfo);
				if(result == 1){
					smsMgrTemplateInfoMapper.addSmsRealtimeControl(mgrId);
					commonService.createSmsOperLog("2", "新增项目【"+mgrId+"】", "0", "项目维护管理");
					if(!"0".equals(tabIndex)){
						commonService.createSmsOperLog("2", "开启项目【"+mgrId+"】", "0", "项目维护管理");
					}
				}else{
					commonService.createSmsOperLog("2", "新增项目【"+mgrId+"】", "1", "项目维护管理");
				}
			} catch (Exception e) {
				e.printStackTrace();
				commonService.createSmsOperLog("2", "新增项目【"+mgrId+"】", "1", "项目维护管理");
				log.error("配置模板属性项目id： " + mgrId);
				throw new SmsException("配置模板属性项目id： " + mgrId);
			}finally {
				if(null != redisCluster){
					try {
						redisCluster.close();
					} catch (Exception e2) {
						log.error("close redis exception :"+ e2.toString());
					}
				}
			}
			if(result == 1){
				result=smsMgrTemplateInfoMapper.updateSmsExtInfo(extId, cityId);
			}
		}else if("modify".equals(flag)){
			try {
				result = smsMgrTemplateInfoMapper.modifyMgrTemplate(smsMgrTemplateInfo);
				commonService.createSmsOperLog("3", "变更项目【"+mgrId+"】", "0", "项目维护管理");
			} catch (Exception e) {
				e.printStackTrace();
				commonService.createSmsOperLog("3", "变更项目【"+mgrId+"】", "1", "项目维护管理");
				log.error("配置模板属性项目id： " + mgrId);
				throw new SmsException("配置模板属性项目id： " + mgrId);
			}

		}

		return result;
	}

//	@SystemServiceLog(description = "添加项目模板信息表", value = false)
	public int configureMgrTemplateQXJ(String cityId,String countyId,String name,String extId,String startTime,String endTime
			,String isLocal,int threshold,String isThreshold,String content,String mgrId,String regionId,String regionType
			,String regionTypeValue,String mgrState,String templateState,String flag
			,String msisdn,String cycle,String cycleThreshold,String localDate,String taskId){

		int result = 0;
		/* if(null==countyId||"".equals(countyId)){
    	        	countyId = cityId;
    	        }*/
		SmsMgrTemplateInfo smsMgrTemplateInfo = new SmsMgrTemplateInfo();
		smsMgrTemplateInfo.setCityId(cityId);
		smsMgrTemplateInfo.setCountyId(countyId);
		smsMgrTemplateInfo.setName(name);
		smsMgrTemplateInfo.setCityExtId(cityId+extId);
		smsMgrTemplateInfo.setStartDate(startTime);
		smsMgrTemplateInfo.setEndDate(endTime);
		smsMgrTemplateInfo.setIsLocal(isLocal);
		smsMgrTemplateInfo.setThreshold(threshold);
		smsMgrTemplateInfo.setIsThreshold(isThreshold);
		smsMgrTemplateInfo.setContent(content);
		smsMgrTemplateInfo.setId(mgrId);
		smsMgrTemplateInfo.setRegionId(regionId);
		smsMgrTemplateInfo.setRegionType(regionType);
		smsMgrTemplateInfo.setRegionTypeValue(regionTypeValue);
		smsMgrTemplateInfo.setMgrState(mgrState);
		smsMgrTemplateInfo.setTemplateState(templateState);
		smsMgrTemplateInfo.setMsisdn(msisdn);
		smsMgrTemplateInfo.setCycle(cycle);
		smsMgrTemplateInfo.setCycleThreshold(cycleThreshold);
		smsMgrTemplateInfo.setLocalDate(localDate);
		smsMgrTemplateInfo.setTaskId(taskId);
		smsMgrTemplateInfo.setCheckNum(1+"");
		smsMgrTemplateInfo.setOpenAccount("1");
		smsMgrTemplateInfo.setContentType("0");
		smsMgrTemplateInfo.setMgrFlag("1");
		if ("insert".equals(flag)) {
			try {
				result = smsMgrTemplateInfoMapper.insertMgrTemplate(smsMgrTemplateInfo);
				if(result == 1){
					smsMgrTemplateInfoMapper.addSmsRealtimeControl(mgrId);
					
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("配置模板属性项目id： " + mgrId);
				throw new SmsException("配置模板属性项目id： " + mgrId);
			}
			if(result == 1){
				result=smsMgrTemplateInfoMapper.updateSmsExtInfo(extId, cityId);
			}
		}else if("modify".equals(flag)){
			try {
				result = smsMgrTemplateInfoMapper.modifyMgrTemplate(smsMgrTemplateInfo);
			} catch (Exception e) {
				e.printStackTrace();
				log.error("配置模板属性项目id： " + mgrId);
				throw new SmsException("配置模板属性项目id： " + mgrId);
			}

		}

		return result;
	}
	//    @SystemServiceLog(description = "更新是否生成csv状态", value = false)
	//    public int updateCsvState(String state){
	////        int result = smsMgrTemplateInfoMapper.updateCsvState(state);
	//    	 int result =1 ;
	//        return result;
	//    }


	//@SystemServiceLog(description = "通过项目id查询项目模板表", value = false)
	public SmsMgrTemplateInfo findMgrTemplateByMgrId(String mgrId) {
		SmsMgrTemplateInfo smsMgrTemplateInfo;
		try {
			smsMgrTemplateInfo = smsMgrTemplateInfoMapper.findMgrTemplateByMgrId(mgrId);
			smsMgrTemplateInfo.setSmsRealtimeControl(smsMgrTemplateInfoMapper.findBySmsRealtimeControlMgrId(mgrId));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查询项目模板表根据项目id： " + mgrId);
			throw new SmsException("查询项目模板表根据项目id： " + mgrId);
		}
		return smsMgrTemplateInfo;
	}

	/**
	 * 重置模板信息
	 * @param map
	 * @return
	 */
	public int resetThreshold(HashMap<String, Object> map){
		int result=0;
		try {
			result=smsMgrTemplateInfoMapper.resetThreshold(map);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("重置模板信息" );
		}
		return  result;
	}
	/**
	 * 修改状态和 是否重新生成csv flag  1 重新生成
	 * @Description:  
	 * @author liurr 
	 * @date 2019年3月20日 下午3:59:41  
	 * @param id
	 * @param cityId
	 * @param mgrState
	 * @param templateState
	 * @return
	 */
	public int modifyMgrState(String id,String cityId,String mgrState,String templateState){
		int result=0;
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("id", id);
		map.put("cityId", cityId);
		map.put("mgrState", mgrState);
		map.put("templateState", templateState);
		try {

			result=smsMgrTemplateInfoMapper.modifyMgrState(map);
			if("0".equals(mgrState)){
				commonService.createSmsOperLog("3", "开启项目【"+ id+"】", "0", "项目维护管理");
			}else if("2".equals(mgrState)){
				commonService.createSmsOperLog("3", "关闭项目【"+ id+"】", "0", "项目维护管理");
			}

//			if("2".equals(templateState)){
//				commonService.createSmsOperLog("3", "审核项目【"+ id+"】-通过", "0", "项目维护管理");
//			}else if("3".equals(templateState)){
//				commonService.createSmsOperLog("3", "审核项目【"+ id+"】-不通过", "0", "项目维护管理");
//			}
			//            if(result>0){
			//                result=smsMgrTemplateInfoMapper.updateCsvState("1");
			//            }
		} catch (Exception e) {
			e.printStackTrace();
			log.error("重置模板信息" );
		}
		return  result;
	}

	/**
	 * 根据id查询地市名称
	 * @author zhangh
	 * @param cityId
	 * @return
	 */
	public String  findCityName(String cityId){
		String cityName = smsMgrTemplateInfoMapper.findCityName(cityId);
		return cityName;
	}
	/**
	 * 更新审核次数
	 * @author zhangh
	 * @param checkNum
	 * @return
	 */
	public int updateCheckNum(String checkNum,String mgrId){
		int result = smsMgrTemplateInfoMapper.updateCheckNum(checkNum,mgrId);
		return result;
	}
}
